package com.yupi.usercenter.base.model;

import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Map;

@Data
@NoArgsConstructor
public class ApiResult<T> {
    //状态码
    private Integer code;

    //返回信息
    private String msg;

    //版本号
    private String version;

    //返回数据
    private T data;

    private ApiResult(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    private ApiResult(ResultCodeEnum resultCodeEnum) {
        if (resultCodeEnum != null) {
            this.code = resultCodeEnum.getCode();
            this.msg = resultCodeEnum.getMsg();
        }
    }

    private ApiResult(T data, String version) {
        this.code = ResultCodeEnum.SUCCESS.getCode();
        this.msg = ResultCodeEnum.SUCCESS.getMsg();
        this.version = version;
        this.data = data;
    }

    public T result() {
        if (ResultCodeEnum.SUCCESS.getCode() != code) {
            throw new ServiceException(code, msg);
        }
        return data;
    }

    /**
     * 成功时候的调用
     */
    public static <T> ApiResult<T> success(T data, String version) {
        return new ApiResult<T>(data, version);
    }

    public static <T> ApiResult<T> success(Map<Object, String> obj) {
        return new ApiResult<T>((T) obj.get("data"), obj.get("version"));
    }

    /**
     * 成功时候的调用
     */
    public static <T> ApiResult<T> success() {
        return new ApiResult<T>(ResultCodeEnum.SUCCESS);
    }

    /**
     * 成功时候的调用
     */
    public static <T> ApiResult<T> success(Integer code, String msg) {
        return new ApiResult<T>(code, msg);
    }


    /**
     * 失败时候的调用
     */
    public static <T> ApiResult<T> error(ResultCodeEnum resultCodeEnum) {
        return new ApiResult<T>(resultCodeEnum);
    }

    /**
     * 失败时候的调用
     */
    public static <T> ApiResult<T> error(Integer code, String msg) {
        return new ApiResult<T>(code, msg);
    }
}
